<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { buildStyles, getColor } from '../utils'

const props = defineProps<{
    width?: string | number
    height?: string | number
    bgColor?: string;
}>()
const placeholderRef = ref<HTMLElement>()

const styles: any = buildStyles(() => {
    const result: Record<string, string> = {}

    if (props.width !== undefined) {
        result.width = typeof props.width === 'number' ? `${props.width}px` : props.width
    }

    if (props.height !== undefined) {
        result.height = typeof props.height === 'number' ? `${props.height}px` : props.height
    }

    if (props.bgColor !== undefined) {
        result.background = getColor(props.bgColor)
    }

    return result
})

onMounted(() => {
    if (placeholderRef.value) {
        const rect = placeholderRef.value.getBoundingClientRect()
        const svg = placeholderRef.value.querySelector('svg')
        const line1 = placeholderRef.value.querySelector('.line1')
        const line2 = placeholderRef.value.querySelector('.line2')
        if (svg) {
            svg.setAttribute('width', `${rect.width}`)
            svg.setAttribute('height', `${rect.height}`)
        }
        if (line1) {
            line1.setAttribute('x2', `${rect.width}`)
            line1.setAttribute('y2', `${rect.height}`)
        }
        if (line2) {
            line2.setAttribute('y1', `${rect.height}`)
            line2.setAttribute('x2', `${rect.width}`)
        }
    }
})
</script>

<template>
    <div class="umrp-placeholder" :style="styles" ref="placeholderRef">
        <svg xmlns="http://www.w3.org/2000/svg" class="background">
            <line x1="0" y1="0" stroke="#ccc" stroke-width="1" class="line1" />
            <line x1="0" y1="0" stroke="#ccc" stroke-width="1" class="line2" />
        </svg>
        <div class="content">
            <slot></slot>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.umrp-placeholder {
    position: relative;
    border: 1px solid #ccc;
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #fff;

    .background {
        position: absolute;
        z-index: 1;
    }

    .content {
        background-color: #fff;
        position: absolute;
        z-index: 2;
    }
}
</style>